package excel

import (
	"data-system/common"
	"data-system/config"
	"data-system/models"
	"data-system/tools"
	"log"
	"strings"

	"github.com/gorilla/websocket"
)

func ChangeExcelToDB(change ExcelChange) {
	nodeType := strings.Replace(change.FileName, config.Cfg().FileSuffix, "", -1)
	log.Println("【监听】本地文件有改动：nodeType=" + nodeType)
	if IsConflict(nodeType) {
		log.Println("【监听】此nodeType冲突未解决，需先解决冲突：nodeType=" + nodeType)
		return
	}
	conflict, err := ExcelToDB(nodeType, false)
	var message models.XMessage

	var messageType string
	var resp = map[string]interface{}{
		"nodeType":   nodeType,
		"isConflict": false,
	}
	if err != nil {
		resp["error"] = err.Error()
		if conflict {
			resp["isConflict"] = true
			messageType = common.WatchChangeConflict
		} else {
			messageType = common.WatchChangeError
		}
	} else {
		messageType = common.WatchChangeComplete
	}
	message = models.BuildOkMessage("none", messageType, resp)
	for _, client := range Clients {
		client.WriteMessage(websocket.TextMessage, []byte(tools.ObjToJson(message)))
	}
}
